import { createSlice } from '@reduxjs/toolkit';

const initialState: {
  listLoading: boolean;
  actionsLoading: boolean;
  totalCount: number;
  entities: any[];
  entity: object;
  error: any;
  key: string;
} = {
  listLoading: false,
  actionsLoading: false,
  totalCount: 0,
  entities: [],
  entity: {},
  error: undefined,
  key: 'id',
};
export const callTypes = {
  list: 'list',
  action: 'action',
};

export const DictSlice = createSlice({
  name: 'dict',
  initialState: initialState,
  reducers: {
    catchError: (state, action) => {
      state.error = `${action.type}: ${action.payload.error}`;
      if (action.payload.callType === callTypes.list) {
        state.listLoading = false;
      } else {
        state.actionsLoading = false;
      }
    },
    startCall: (state, action) => {
      state.error = null;
      if (action.payload.callType === callTypes.list) {
        state.listLoading = true;
      } else {
        state.actionsLoading = true;
      }
    },
    entitiesFetched: (state, action) => {
      const { totalCount, entities } = action.payload;
      state.listLoading = false;
      state.error = null;
      state.entities = entities;
      state.totalCount = totalCount;
    },
    entityCreated: (state, action) => {
      state.actionsLoading = false;
      state.error = null;
      // state.totalCount = state.totalCount + 1;
      // state.entities.unshift({
      //   ...action.payload.entity,
      //   // ctime: new Date(),
      // });
    },
    setEntity: (state, action) => {
      state.error = null;
      state.entity = action.payload.entity;
    },
    entityDeleted: (state, action) => {
      state.error = null;
      state.actionsLoading = false;
      state.entities = state.entities.filter(
        (el) => el[state.key] !== action.payload.key
      );
    },
    entityUpdated: (state, action) => {
      state.error = null;
      state.actionsLoading = false;
      // state.entity = action.payload.entity;
      // state.entities = state.entities.map((entity) =>
      //   entity[state.key] === action.payload.entity[state.key]
      //     ? action.payload.entity
      //     : entity
      // );
    },
  },
});
